package com.module.my.view

import android.content.Intent
import android.net.Uri
import android.text.InputType
import android.text.TextUtils
import android.view.Gravity
import android.view.ViewGroup
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import androidx.core.widget.TextViewCompat
import com.module.app.base.BaseListFragment
import com.module.app.ext.loginFlow
import com.module.app.ext.modifyUserFlow
import com.app.hubert.guide.NewbieGuide
import com.app.hubert.guide.core.Controller
import com.app.hubert.guide.model.GuidePage
import com.app.hubert.guide.model.HighLight
import com.app.hubert.guide.model.HighlightOptions
import com.app.hubert.guide.model.RelativeGuide
import com.module.app.bean.ListViewBean
import com.module.app.pop.ListPop
import com.module.app.pop.PayPop
import com.module.app.pop.ProgressPop
import com.module.app.utils.UpdateUtils
import com.module.base.base.adapter.BaseNewAdapter
import com.module.base.utils.*
import com.module.app.widget.keyboard.InputBuilder.OnMyClickListener
import com.module.base.base.adapter.BaseAdapter
import com.module.frame.ext.observe
import com.module.my.R
import com.module.my.adapter.holder.MyHolder
import com.module.my.bean.IMyType
import com.module.my.bean.MyBean
import com.module.my.databinding.MyFragMyBinding
import com.module.my.model.MyViewModel
import com.module.my.utils.*
import com.module.third.bean.IThirdType
import com.module.third.qq.QQUtils
import com.module.third.wx.WxUtils
import org.apache.commons.lang3.StringUtils
import java.math.BigDecimal

class MyFragment : BaseListFragment<MyViewModel, MyFragMyBinding, BaseAdapter>() {

    private var progressPop: ProgressPop? = null
    private var controller: Controller? = null
    private val mLauncherService: com.module.app.arouter.service.ILauncherService by lazy {
        com.module.app.arouter.ArouterUtils.getLauncherService()
    }

    override fun bingViewModel() {
        mDatabind.vm = mViewModel
    }

    override fun createAdapter(): BaseAdapter {
        return object : BaseAdapter() {
            override fun onCreateDefaultViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
                return MyHolder(parent)
            }
        }
    }

    override fun onLazyLoad() {
        reload()
    }


    override fun initView() {
        super.initView()
        setCommonTitle(R.string.my_title, false)
        TextViewCompat.setTextAppearance(tvTitle!!, R.style.TextItemTitle)
    }

    override fun initListener() {
        super.initListener()
        //登录监听
        observe(loginFlow) {
            mViewModel.getUser()
        }
        //用户信息更改
        observe(modifyUserFlow) {
            setUserData()
        }
        //设置用户信息
        observe(mViewModel.userDataFlow) {
            setUserData()
        }
        //绑定
        observe(mViewModel.bindingFlow) {
            alreadyBinding(it)
        }
        //获取支付信息
        observe(mViewModel.priceFow) {
            setPrice(it.payBean, it.price, it.text)
        }
        adapter.setOnItemClickListener(BaseNewAdapter.OnItemClickListener<MyHolder?, MyBean> { holder, bean ->
            when (bean.listType) {
                IMyType.IListType.vip -> context.startVip()
                IMyType.IListType.problem -> context.startProblem()
                IMyType.IListType.pay -> pay(bean.name ?: "")
                IMyType.IListType.feedback ->
                    mLauncherService.let {
                        it.goMsg(context)
                        ToastUtils.showShort(R.string.my_go_feedback)
                    }
                IMyType.IListType.kefu -> {
                    val list: MutableList<com.module.app.bean.ListData> = mutableListOf()
                    list.add(com.module.app.bean.ListData(1, "微信", true))
                    list.add(com.module.app.bean.ListData(2, "QQ", true))
                    if (!TextUtils.isEmpty(com.module.app.bean.ConfigBean.getInstance().qqGroupKey)) {
                        list.add(com.module.app.bean.ListData(3, "QQ群", true))
                    }
                    val qq = "1218968265"
                    val wx = "19906058322"
                    ListPop.show(context, list, object : ListPop.Listener {
                        override fun onClick(listData: com.module.app.bean.ListData) {
                            when (listData.type) {
                                1 -> {
                                    CommonUtils.copyToClipBoard(context, wx)
                                    ToastUtils.showShort(com.module.base.R.string.copy_suc)
                                    context?.let {
                                        WxUtils(it, lifecycle).jumpWx(it)
                                    }
                                }
                                2 -> {
                                    QQUtils(lifecycle).jumpQQFriend(context, qq)
                                }
                                3 -> {
                                    QQUtils(lifecycle).jumpQQGroup(
                                        context,
                                        com.module.app.bean.ConfigBean.getInstance().qqGroupKey
                                    )
                                }
                            }
                        }
                    })
                }
                IMyType.IListType.share -> onClickShare()
                IMyType.IListType.evaluate -> try {
                    val uri = Uri.parse("market://details?id=" + context?.packageName)
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent)
                    ToastUtils.showShort("记得给好评哦~")
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
                IMyType.IListType.New -> setUpDate()
                IMyType.IListType.set -> context.startSet()
                IMyType.IListType.inviteCode -> bindingInviteCode(bean.name ?: "")
                IMyType.IListType.skin -> context.startSkin()
            }
        })
        mDatabind.layoutHead.setOnClickListener {
            onClickHead()
        }
        mDatabind.layoutHead.setOnLongClickListener {
            onLongClickHead()
            false
        }

    }


    override fun initData() {
        super.initData()
        mViewModel.getUser()
    }


    override fun onListLoadPage(
        isPull: Boolean,
        isRefresh: Boolean,
        page_no: Int,
        page_size: Int
    ) {
        mViewModel.getData()
        setUserData()
    }

    private fun setUserData() {
        if (com.module.app.utils.UserUtils.isLogin()) {
            mDatabind.tvName.text =
                if (com.module.app.utils.UserUtils.getName().isNullOrEmpty()) CommonUtils.getString(
                    R.string.my_not_filled
                ) else com.module.app.utils.UserUtils.getName()
        } else {
            mDatabind.tvName.setText(R.string.my_click_login)
        }
        if (com.module.app.utils.UserUtils.isLogin()) {
            if (StringUtils.isBlank(com.module.app.utils.UserUtils.getHeadUrl())) {
                mDatabind.ivHead.setImageResource(R.drawable.my_icon_male)
            } else {
                com.module.app.utils.GlideUtils.loadNet(
                    mDatabind.ivHead.context,
                    mDatabind.ivHead,
                    com.module.app.utils.UserUtils.getHeadUrl()
                )
            }
        } else {
            mDatabind.ivHead.setImageResource(R.drawable.my_icon_male)
        }
        //设置我的vip
        for (i in adapter.data.indices) {
            var mObject = adapter.data[i]
            if (mObject is MyBean) {
                val myBean = mObject
                if (myBean.listType != IMyType.IListType.vip) {
                    continue
                }
                var right: String? = ""
                if (com.module.app.utils.UserUtils.isLogin()) {
                    right = com.module.app.utils.UserUtils.getVipExpiration()
                    myBean.right = right
                    adapter.notifyItemChangedAndHead(i)
                }
            }
        }
    }

    private fun setUpDate() {
        //弹窗更新
        progressPop = ProgressPop.Builder(context)
            .setContentGravity(Gravity.LEFT)
            .setTitle(R.string.update_title)
            .setProgressTitle(R.string.downloading)
            .setContent(com.module.app.bean.ConfigBean.getInstance().appVersionContent)
            .setAutoDismiss(false)
            .setCancelButton(R.string.update_cancel)
            .setConfirmButton(R.string.right_off_update)
            .setOnCancelListener { progressPop?.dismiss() }
            .setOnConfirmListener {
                UpdateUtils.update(
                    mActivity,
                    com.module.app.bean.ConfigBean.getInstance().downloadApk,
                    com.module.app.bean.ConfigBean.getInstance().appVersionName
                )
            }
            .create()
        progressPop?.show()
    }

    private fun pay(title: String) {
        com.module.app.widget.keyboard.InputConfirmDialog.Builder(context)
            .setTitle(title)
            .setContent(R.string.my_naicha_price_content)
            .setInputType(InputType.TYPE_CLASS_NUMBER)
            .setEditHint(R.string.my_naicha_price_hint)
            .setConfirmButton(R.string.confirm)
            .setCancelButton(R.string.cancel)
            .setOnConfirmListener(object : OnMyClickListener() {
                override fun onClick(dialog: com.module.app.widget.keyboard.InputConfirmDialog, text: String) {
                    if (TextUtils.isEmpty(text)) {
                        ToastUtils.showShort(R.string.my_naicha_price_empty)
                        return
                    }
                    mViewModel.getPay(text, title)
                    dialog.hide()
                }
            }).show()
    }

    fun setPrice(bean: com.module.app.bean.PayBean, price: String, text: String) {
        var dPrice = BigDecimal(0.01)
        try {
            dPrice = BigDecimal(price)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        PayPop.show(context, IThirdType.IBuyType.donation, bean, dPrice, text)
    }

    fun onClickShare() {
//        ShareDialog.Builder(context)
//            .setLayoutType(ShareLayoutType.TYPE_NORMAL)
//            .setLayoutData(Share("私人空间-加密隐私", "加密安全，保护您的隐私。", ConfigBean.getInstance().qrCode))
//            .setShareButtonListener(ShareButtonListener { shareType, text ->
//                if (UserUtils.isLogin()) {
//                    ToastUtils.showLong("邀请口号已复制，请粘贴在聊天框发送出去。");
//                    CommonUtils.copyToClipBoard(
//                        context,
//                        "邀请你来一起加密图片。\n我的邀请码：【" + UserUtils.getUserId() + "】\n邀请即可获得无门槛优惠券\n(直接复制整段即可)"
//                    );
//                } else {
//                    ToastUtils.showLong("请登录后，获取邀请口号");
//                }
//            }).show()
    }


    /**
     * 绑定邀请码
     */
    private fun bindingInviteCode(title: String) {
        if (!com.module.app.utils.UserUtils.isLogin(true)) {
            return
        }
        if (!com.module.app.utils.UserUtils.getInviter().isNullOrEmpty()) {
            mViewModel.getBindingUser(com.module.app.utils.UserUtils.getInviter())
            return
        }
        com.module.app.widget.keyboard.InputConfirmDialog.Builder(context)
            .setTitle(title)
            .setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD)
            .setEditHint(R.string.my_binding_invite_code_hint)
            .setEditText(CommonUtils.getInviteCode())
            .setConfirmButton(R.string.binding)
            .setCancelButton(R.string.cancel)
            .setOnConfirmListener(object : OnMyClickListener() {
                override fun onClick(dialog: com.module.app.widget.keyboard.InputConfirmDialog, text: String) {
                    if (TextUtils.isEmpty(text)) {
                        ToastUtils.showShort(R.string.my_binding_invite_code_empty)
                        return
                    }
                    dialog.hide()
                }
            }).show()
    }

    private fun alreadyBinding(bean: com.module.app.bean.UserBean?) {
        if (bean == null) {
            return
        }
        com.module.app.pop.CommonPop.Builder(context)
            .setContent(
                String.format(CommonUtils.getString(R.string.my_already_binding), bean.name)
            )
            .show()
    }

    override fun setListData(bean: ListViewBean) {
        super.setListData(bean)
        if (bean.isRefresh && !CollectionUtil.isEmptyOrNull(bean.list)) {
            recyclerview?.postDelayed({ showGuide() }, 100)
        }
    }

    private fun showGuide() {
        if (activity == null || activity?.isFinishing == true) {
            return
        }
        val position = 1
        val viewHolder = adapter.getViewHolder(position)
        val enterAnimation: Animation = AlphaAnimation(0f, 1f)
        enterAnimation.duration = 300
        enterAnimation.fillAfter = true
        val exitAnimation: Animation = AlphaAnimation(1f, 0f)
        exitAnimation.duration = 300
        exitAnimation.fillAfter = true


        //图片
        val options = HighlightOptions.Builder()
            .setOnClickListener {
                controller?.let {
                    it.remove()
                }
                context.startProblem()
            }
            .setRelativeGuide(
                RelativeGuide(R.layout.my_guide_problem, Gravity.BOTTOM)
            )
            .build()
        val page = GuidePage.newInstance()
            .addHighLightWithOptions(
                viewHolder.itemView,
                HighLight.Shape.ROUND_RECTANGLE,
                DisplayUtils.dip2px(10f),
                DisplayUtils.dip2px(1f),
                options
            )
            .setEnterAnimation(enterAnimation)
            .setExitAnimation(exitAnimation)
            .setEverywhereCancelable(true) //点击任何地方都能取消
        controller = NewbieGuide.with(this)
            .setLabel("problem_tips")
            .addGuidePage(page)
            .show()
    }


    private fun onClickHead() {
        context.startUser()
    }

    private fun onLongClickHead() {
        com.module.app.pop.CommonPop.Builder(context)
            .setTitle("用户Id")
            .setContent("当遇到问题，提供该ID寻找客服排查问题。\n用户Id:" + com.module.app.utils.UserUtils.getUserId())
            .setConfirmButton(R.string.copy)
            .setOnConfirmListener {
                CommonUtils.copyToClipBoard(context, com.module.app.utils.UserUtils.getUserId())
                ToastUtils.showShort("复制成功")
            }
            .show()
    }

    override fun setBackground(isBackground: Boolean) {
        super.setBackground(isBackground)
        if (isBackground) {
            mDatabind.ivUserBg.alpha = 0.7f
        } else {
            mDatabind.ivUserBg.alpha = 1f
        }
    }
}